package com.example.liben.zyfypt709__gdc.model;

import com.example.liben.zyfypt709__gdc.bean.LoginBean;
import com.example.liben.zyfypt709__gdc.common.Common;
import com.example.liben.zyfypt709__gdc.iface.LoginListener;
import com.example.liben.zyfypt709__gdc.iface.Loginiface;
import com.example.liben.zyfypt709__gdc.service.UserService;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class LoginModel implements Loginiface {
    private Retrofit retrofit;
    //构造方法
    public LoginModel(){

                 retrofit = new Retrofit.Builder()
                .baseUrl(Common.BASEURL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

    }

    //实现Loginiface中的方法
    @Override
    public void getLoginResult(String username, String password, final LoginListener loginListener) {

        UserService service = retrofit.create(UserService.class);
        Call<LoginBean> call = service.login(username,password);

        call.enqueue(new Callback<LoginBean>() {
            @Override
            public void onResponse(Call<LoginBean> call, Response<LoginBean> response) {
                if(response.isSuccessful() && response.body()!=null)
                {
                    loginListener.onResponse(response.body());
                }
                else
                {
                    loginListener.onFail("onResponse fail");
                }
            }

            @Override
            public void onFailure(Call<LoginBean> call, Throwable t) {
                    loginListener.onFail(t.toString());
            }
        });
    }


}
